// api/ai_role_api/ai_role_update_user.go
package ai_role_api

import (
	"encoding/json"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/jwts"
	"muziai-server/utils/ref"
	"muziai-server/utils/res"

	"github.com/gin-gonic/gin"
)

type AiRoleUpdateUserRequest struct {
	RoleID   uint    `json:"roleID" binding:"required"`
	Title    *string `json:"title" mps:"title"`
	Avatar   *string `json:"avatar" mps:"avatar"`
	Category *string `json:"category" mps:"category"` // 角色分类
	Abstract *string `json:"abstract" mps:"abstract"`
	Prompt   *string `json:"prompt" mps:"prompt"` // 提示词
	Reason   string  `json:"reason"`              // 工单理由
}

func (AiRoleApi) AiRoleUpdateUserView(c *gin.Context) {
	var cr AiRoleUpdateUserRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)
	var model models.AiRoleModel
	err = global.DB.
		Take(&model, "id = ? and user_id = ?", cr.RoleID, claims.UserID).Error
	if err != nil {
		res.FailWithMsg(c, "角色不存在")
		return
	}
	if cr.Title != nil {
		var m models.AiRoleModel
		err = global.DB.Take(&m, "user_id = ? and title = ? and id <> ?", claims.UserID, *cr.Title, cr.RoleID).Error
		if err == nil {
			res.FailWithMsg(c, "更新的角色名称重复")
			return
		}
	}

	if !model.IsSquare {
		// 不在角色广场，直接更新传了的字段
		maps, _ := ref.StructToMapByMaps(cr)
		err = global.DB.Model(&model).Updates(maps).Error
		if err != nil {
			res.FailWithMsg(c, "角色更新失败")
			return
		}
		res.OkWithMsg(c, "角色更新成功")
		return
	}
	if cr.Reason == "" {
		res.FailWithMsg(c, "请输入申请理由")
		return
	}

	if cr.Title != nil && *cr.Title != "" {
		model.Title = *cr.Title
	}
	if cr.Avatar != nil && *cr.Avatar != "" {
		model.Avatar = *cr.Avatar
	}
	if cr.Category != nil && *cr.Category != "" {
		model.Category = *cr.Category
	}
	if cr.Abstract != nil && *cr.Abstract != "" {
		model.Abstract = *cr.Abstract
	}
	if cr.Prompt != nil && *cr.Prompt != "" {
		model.Prompt = *cr.Prompt
	}

	byteData, _ := json.Marshal(model)
	// 在角色广场里面的，创建工单
	err = global.DB.Create(&models.AiRoleWorkOrderModel{
		Reason:           cr.Reason,
		UserID:           claims.UserID,
		AiRoleID:         cr.RoleID,
		Type:             2,
		Status:           1,
		AiRoleUpdateData: string(byteData),
	}).Error
	if err != nil {
		res.FailWithMsg(c, "创建工单失败")
		return
	}
	res.OkWithMsg(c, "已创建角色更新工单")
}
